package com.guage.producter.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.guage.producter.domain.User;
import com.guage.producter.result.JSONResult;
import com.guage.producter.service.IUserService;
import com.guage.producter.utils.SnowflakeIdWorker;
import com.pad.dpscn.daag.sdk.core.annotation.DataSendPosition;

import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.update.Update;

/**
 * @desc
 * @author yangdechao
 * @since 2021-12-21
 */
@RestController
@RequestMapping("/user")
@Slf4j
@DataSendPosition
public class UserController {

	@Autowired
	public IUserService userService;

	/**
	 * 保存和修改操作公用此方法
	 * 
	 * @param operLog 前端传递来的实体数据
	 */
	@GetMapping(value = "/selectById/{id}")
	public JSONResult selectById(@PathVariable("id") String id) {
		User entity = userService.selectById(id);
		return JSONResult.success(entity);
	}

	/**
	 * 保存和修改操作公用此方法
	 * 
	 * @param operLog 前端传递来的实体数据
	 */
	@PostMapping(value = "/save")
	public JSONResult save(@RequestBody User user) {
		log.info("======================业务执行开始=====================");
		SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1, 1);
		long id = idWorker.nextId();
		user.setId(id + "");
		userService.insert(user);
		log.info("======================业务执行结束=====================");

		return JSONResult.success();
	}

	/**
	 * 保存和修改操作公用此方法
	 * 
	 * @param operLog 前端传递来的实体数据
	 */
	@PostMapping(value = "/saveAndUpdate")
	public JSONResult saveAndUpdate(@RequestBody User user) {
		user.setId(UUID.randomUUID().toString());
		userService.insert(user);
		Random random = new Random(100);
		user.setUserName(random.nextInt() + "用户名");
		userService.updateById(user);
		return JSONResult.success();
	}

	/**
	 * 根据ID删除指定对象信息
	 * 
	 * @param id
	 */
	@DeleteMapping(value = "/deleteById/{id}")
	public JSONResult delete(@PathVariable("id") String id) {
		userService.deleteById(id);
		return JSONResult.success();
	}
	
	/**
	 * 根据ID删除指定对象信息
	 * 
	 * @param id
	 */
	@DeleteMapping(value = "/deleteAll")
	public JSONResult deleteAll() {
		userService.delete(null);
		return JSONResult.success();
	}


	/**
	 * 保存和修改操作公用此方法
	 * 
	 * @param operLog 前端传递来的实体数据
	 */
	@PostMapping(value = "/updateById")
	public JSONResult updateById(@RequestBody User user) {
		log.info("------------开始执行user updateById方法----------------");
		userService.updateById(user);
		log.info("-----------user updateById方法执行完毕----------------");

		return JSONResult.success();
	}

	@PostMapping(value = "/updateUserByParams")
	public JSONResult updateUserByParams(@RequestBody User user) {
		// QueryWrapper<User> queryWrapperUser = new QueryWrapper<>();
		log.info("------------开始执行user updateData方法----------------");
		user.setLoginName("批量修改");
		user.setPasswd("批量修改");
		// 条件构造器作为参数进行更新(user可以设置多个属性 ， user属性为set = "value" 条件构造器为where字句的条件)
		userService.updateUserByParams(user);
		log.info("-----------user updateData方法执行完毕----------------");
		return JSONResult.success();
	}

	@GetMapping(value = "/updateAllColumnBatchById")
	public JSONResult updateAllColumnBatchById() {
		List<User> entityList = new ArrayList<User>();
		for (Long i = (long) 101; i <= 110; i++) {
			User user = new User();
			user.setId(i + "");
			user.setPasswd("10086");
			user.setDeptId("10000");
			user.setUserName("批量更新");
			user.setLoginName("批量更新");
			user.setUpdateTime(new java.util.Date());
			entityList.add(user);
		}
		// 条件构造器作为参数进行更新(user可以设置多个属性 ， user属性为set = "value" 条件构造器为where字句的条件)
		userService.updateAllColumnBatchById(entityList);
		return JSONResult.success();
	}

	/**
	 * 并发条件测试
	 * @return
	 */
	@GetMapping(value = "/updateAllColumnBatchByIdThreadSafeTest")
	public JSONResult updateAllColumnBatchByIdThreadSafeTest() {

		for (int j = 0; j < 5; j++) {
			new Thread(() -> {
				List<User> entityList = new ArrayList<User>();
				for (Long i = (long) 100; i < 105; i++) {
					User user = new User();
					user.setId(i + "");
					user.setLoginName("批量更新");
					entityList.add(user);
				}
				// 条件构造器作为参数进行更新(user可以设置多个属性 ， user属性为set = "value" 条件构造器为where字句的条件)
				userService.updateAllColumnBatchById(entityList);
			}, String.valueOf(j)).start();
		}
		
		return JSONResult.success();
	}

	public static String parseWhereQueryCondition(String comlpateSQL, String sqlCommandType) {
		String condition = "";
		try {
			net.sf.jsqlparser.statement.Statement statement = (net.sf.jsqlparser.statement.Statement) CCJSqlParserUtil
					.parse(comlpateSQL);
			if ("UPDATE".equals(sqlCommandType)) {
				Update update = (Update) statement;
				Expression expression = update.getWhere();
				condition = expression.toString();
			}
			if ("DELETE".equals(sqlCommandType)) {
				Delete delete = (Delete) statement;
				Expression expression = delete.getWhere();
				condition = expression.toString();
			}
		} catch (JSQLParserException e) {
			e.printStackTrace();
		}
		return condition;
	}

	public static String getWhere(String sql) throws JSQLParserException {
		String condition = "";
		String pattern = "(?i)(update|delete)\\s+[\\w\\s,]*\\s+(?i)(WHERE)\\s+(.*?)(?=\\s*;$|$)"; // 匹配WHERE后面的任意字符
		Pattern r = Pattern.compile(pattern);
		Matcher m = r.matcher(sql);
		if (m.find()) {
			condition = m.group(1);
		}
		log.info("where 条件为：" + condition);

		return condition;
	}
}